package sm.hibernate.sql;

import org.hibernate.sql.ConditionFragment;
import org.hibernate.util.ArrayHelper;

public class SMConditionFragment extends ConditionFragment {
	private String tableAlias;
	private String[] lhs;
	private String[] rhs;
	private String op = "=";

	/**
	 * Sets the op.
	 * 
	 * @param op
	 *            The op to set
	 */
	public SMConditionFragment setOp(String op) {
		this.op = op;
		return this;
	}

	/**
	 * Sets the tableAlias.
	 * 
	 * @param tableAlias
	 *            The tableAlias to set
	 */
	public SMConditionFragment setTableAlias(String tableAlias) {
		this.tableAlias = tableAlias;
		return this;
	}

	public SMConditionFragment setCondition(String[] lhs, String[] rhs) {
		this.lhs = lhs;
		this.rhs = rhs;
		return this;
	}

	public SMConditionFragment setCondition(String[] lhs, String rhs) {
		this.lhs = lhs;
		this.rhs = ArrayHelper.fillArray(rhs, lhs.length);
		return this;
	}

	public String toFragmentString() {
		StringBuffer buf = new StringBuffer(lhs.length * 10);
		for (int i = 0; i < lhs.length; i++) {
			buf.append("((").append(tableAlias).append('.').append(lhs[i])
					.append(op).append(rhs[i]).append(") or (").append(rhs[i])
					.append(" is null and ").append(tableAlias).append('.')
					.append(lhs[i]).append(" is null))");
			if (i < lhs.length - 1)
				buf.append(" and ");
		}
		return buf.toString();
	}

}
